package wiki.zimo.certificate_manage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author 子墨
 * @date 2018/10/14 9:49
 * @describe 处理文件请求
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Value("${file.upload-path}")
    private String uploadPath;// 文件保存路径
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 返回文件接口，可以返回上传到本地的图片，视频，静态资源等
     * @author 子墨
     * @date 2018/8/17 17:55
     * @params [fileName]
     * @return org.springframework.http.ResponseEntity
     */
    @RequestMapping(value = "",produces = {"image/jpg"})
    public ResponseEntity returnFile(@RequestParam("filename") String fileName){
        try {
            // 请求的是静态资源
            if (fileName.contains("/static/")){
                // 在Controller里面可以直接请求到/static/下的静态资源，由于配置了项目的context-path，处理一下这类请求
                if (!fileName.startsWith("/static/")){
                    fileName = fileName.substring(fileName.indexOf("/static/"));
                }
                fileName = new ClassPathResource(fileName).getPath();
                return ResponseEntity.ok(resourceLoader.getResource("classpath:" + fileName));
            }
            // 请求的文件资源
            return ResponseEntity.ok(resourceLoader.getResource("file:" + uploadPath + fileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }


}
